package com.glela.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.glela.api.model.PayAppKeyInfo;
import com.glela.api.pay.wechat.component.WeChat;
import com.glela.api.pay.wechat.component.impl.WeChat0Impl;
import com.glela.api.pay.wechat.component.impl.WeChatImpl;
import com.glela.api.pay.wechat.vo.JsapiTicketVo;
import com.glela.api.pay.wechat.vo.WeChaShareRequest;
import com.glela.api.pay.wechat.vo.WeChatPayRequest;
import com.glela.api.pay.wechat.vo.WeChatTokenVo;
import com.glela.api.pay.wechat.vo.WeChatUserInfoVo;
import com.glela.common.constant.PayTypeEnum;
import com.glela.common.util.JsonUtil;
import com.glela.common.util.NetworkUtil;
import com.glela.common.util.RandomUtil;
import com.glela.order.mapper.OrderObjectMapper;
import com.glela.order.mapper.OrderPayMapper;
import com.glela.order.mapper.OrderSettlementCommisionMapper;
import com.glela.order.model.AfterSales;
import com.glela.order.model.OrderObject;
import com.glela.order.model.OrderPay;
import com.glela.order.model.OrderSettlementCommision;
import com.glela.order.service.AfterSalesService;
import com.glela.order.service.OrderPayService;
import com.glela.order.service.OrderService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.User;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.UserService;
import com.glela.platform.util.ParameterUtils;
import com.glela.statistics.service.UserEarningsService;
import com.glela.talent.model.OrderVip;
import com.glela.talent.service.TalentService;

/**
 * @author liujie
 * @2016年11月1日
 */
@Controller
@RequestMapping("wecha")
public class WeChaController {
	
	private static Logger logger = LoggerFactory.getLogger(WeChaController.class);
	
	@Resource(name = "orderService2")
	private OrderService orderService2;
	
	@Autowired
	private List<WeChat> weChatList;
	
	@Autowired
	private OrderPayMapper orderPayMapper;
	@Autowired
	private OrderSettlementCommisionMapper orderSettlementCommisionMapper;
	
	@Autowired
	private TalentService talentService;
	
	@Autowired
	private AfterSalesService afterSalesService;
	
	@Autowired
	private UserService userService;
	@Autowired
	private OrderObjectMapper orderObjectMapper;
	@Autowired
	private UserEarningsService userEarningsService;
	
	/**
	 * 获得分享accessToken
	 * 
	 */
	@RequestMapping(value = "/getAccessToken", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getAccessToken() {
		try {
			PayAppKeyInfo payAppKeyInfo=getOrderService().getPayAppKeyInfo(PayTypeEnum.T3.getCode());
			WeChatTokenVo vo = getWeChat(PayTypeEnum.T3.getCode()).getAccessToken(payAppKeyInfo.getAppId(), payAppKeyInfo.getSecret());
			if (vo == null ) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29911), HttpStatus.OK);
			}else {
				return new ResponseEntity<>(new ResponseResultModel<>(vo), HttpStatus.OK);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 * 获得分享用的JsapiTicket
	 * @param response
	 * @param request
	 */
	@RequestMapping(value = "/getJsapiTicket", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getJsapiTicket(@RequestBody WeChaShareRequest weChaShareRequest) {
		try {
			if (ParameterUtils.validParams(weChaShareRequest.getAccessToken()))
			{
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			JsapiTicketVo vo = getWeChat(PayTypeEnum.T3.getCode()).getJsapiTicket(weChaShareRequest.getAccessToken());
			if (vo == null ) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29911), HttpStatus.OK);
			}else {
				return new ResponseEntity<>(new ResponseResultModel<>(vo), HttpStatus.OK);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 * 查询微信分享
	 * 
	 */
	@RequestMapping(value = "/getWeChaShare", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getWeChaShare(@RequestBody WeChaShareRequest weChaShareRequest) {
		try {
			if (ParameterUtils.validParams(weChaShareRequest.getJsapiTicket(),weChaShareRequest.getUrl()))
			{
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			
			Map<String, String> map = new HashMap<String, String>();
			//随机数 
			String noncestr = RandomUtil.getRandomNumber(10) ;
			map.put("noncestr", noncestr); 
			map.put("jsapi_ticket", weChaShareRequest.getJsapiTicket()) ;
			map.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
			map.put("url", weChaShareRequest.getUrl());
			
			String sharSign = getWeChat(PayTypeEnum.T3.getCode()).getShareSign(map);
			return new ResponseEntity<>(new ResponseResultModel<>(sharSign), HttpStatus.OK);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 * 微信授权信息
	 * 
	 */
	@RequestMapping(value = "/getWeChaAuthority", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getWeChaAuthority(@RequestBody WeChatPayRequest weChatPayRequest) {
		try {
			if (ParameterUtils.validParams(weChatPayRequest.getCode(),weChatPayRequest.getPayType()))
			{
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			PayAppKeyInfo payAppKeyInfo=getOrderService().getPayAppKeyInfo(weChatPayRequest.getPayType());
			WeChatTokenVo vo =getWeChat(weChatPayRequest.getPayType())
					.getWeChaAuthority(payAppKeyInfo.getAppId(), payAppKeyInfo.getSecret(), weChatPayRequest.getCode()) ;
			if (vo == null ) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29911), HttpStatus.OK);
			}else {
				return new ResponseEntity<>(new ResponseResultModel<>(vo), HttpStatus.OK);
			}
		} catch (IOException e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 刷新access_token
	 * 
	 */
	@RequestMapping(value = "/getRefreshToken", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getRefreshToken(@RequestBody WeChatPayRequest weChatPayRequest) {
		try {
			if (ParameterUtils.validParams(weChatPayRequest.getRefreshToken(),weChatPayRequest.getPayType()))
			{
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			PayAppKeyInfo payAppKeyInfo=getOrderService().getPayAppKeyInfo(weChatPayRequest.getPayType());
			WeChatTokenVo vo =getWeChat(weChatPayRequest.getPayType())
					.getRefreshToken(payAppKeyInfo.getAppId() , weChatPayRequest.getRefreshToken()) ;
			if (vo == null ) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29911), HttpStatus.OK);
			}else {
				return new ResponseEntity<>(new ResponseResultModel<>(vo), HttpStatus.OK);
			}
		} catch (IOException e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 * 拉取用户信息(需scope为 snsapi_userinfo)
	 * 
	 */
	@RequestMapping(value = "/getUserInfo", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getUserInfo(@RequestBody WeChatPayRequest weChatPayRequest) {
		try {
			if (ParameterUtils.validParams(weChatPayRequest.getAccessToken(),weChatPayRequest.getOpenId(),weChatPayRequest.getPayType()))
			{
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			WeChatUserInfoVo vo =getWeChat(weChatPayRequest.getPayType())
					.getUserInfo(weChatPayRequest.getAccessToken(), weChatPayRequest.getOpenId()) ;
			if (vo == null ) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29911), HttpStatus.OK);
			}else {
				return new ResponseEntity<>(new ResponseResultModel<>(vo), HttpStatus.OK);
			}
		} catch (IOException e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 * 检验授权凭证（access_token）是否有效
	 * @param response
	 * @param request
	 */
	@RequestMapping(value = "/getIsOkAccessToken", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getIsOkAccessToken(@RequestBody WeChatPayRequest weChatPayRequest) {
		try {
			if (ParameterUtils.validParams(weChatPayRequest.getAccessToken(),weChatPayRequest.getOpenId(),weChatPayRequest.getPayType()))
			{
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			WeChatTokenVo vo =getWeChat(weChatPayRequest.getPayType())
					.getIsOkAccessToken(weChatPayRequest.getAccessToken(), weChatPayRequest.getOpenId()) ;
			if (vo == null ) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29911), HttpStatus.OK);
			}else {
				return new ResponseEntity<>(new ResponseResultModel<>(vo), HttpStatus.OK);
			}
		} catch (IOException e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 * 微信支付
	 * @param response
	 * @param request
	 */
	@RequestMapping(value = "/weChaPay", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> weChaPay(@RequestBody WeChatPayRequest weChatPayRequest, HttpServletRequest request) {
		try {
			if (ParameterUtils.validParams(weChatPayRequest.getOrderSn())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102,"缺少订单号"), HttpStatus.OK);
			}
			if (ParameterUtils.validParams( weChatPayRequest.getPayType())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102,"缺少支付方式"), HttpStatus.OK);
			}
			if (weChatPayRequest.getPayType() == PayTypeEnum.T3.getCode()) {
				if (ParameterUtils.validParams(weChatPayRequest.getOpenId())) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102,"公众号支付,缺少OPENID"), HttpStatus.OK);
				}
			} else if (weChatPayRequest.getPayType() == PayTypeEnum.T1.getCode()) {
			} else {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102, "暂不支持"), HttpStatus.OK);
			}

			OrderObject orderObject = getOrderService().selectOrderObjectByOrderSn(weChatPayRequest.getOrderSn());
			if (orderObject == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20802), HttpStatus.OK);
			}

			if(orderObject.getOpenStore() == 1){
				if(weChatPayRequest.getPayType() != 22){
					//return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20418), HttpStatus.OK);
				}
			}
			logger.error("用户发起支付宝支付, 父订单号: {} , 开店单标识: {}", orderObject.getOrderSn(), orderObject.getOpenStore());
			if (orderObject.getStatus().intValue()!=1) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20802,"该笔订单暂时无法支付"), HttpStatus.OK);
			}
			String ipAddress = NetworkUtil.getRealIp(request);
			Map<String, Object> outmap = orderPayService.saveWxPay(orderObject.getOrderSn(), weChatPayRequest.getPayType(), orderObject.getTotalFee(), ipAddress, weChatPayRequest.getOpenId(), getWeChat(weChatPayRequest.getPayType()));
			
			//			PayAppKeyInfo payAppKeyInfo = getOrderService().getPayAppKeyInfo(weChatPayRequest.getPayType());
			//						Map<String, Object> outmap = getWeChat(weChatPayRequest.getPayType()).weChaPay(payAppKeyInfo, weChatPayRequest.getOrderSn(), orderObject.getTotalFee(), request.getRemoteAddr(), weChatPayRequest.getOpenId());
			return new ResponseEntity<>(new ResponseResultModel<>(outmap), HttpStatus.OK);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	/**
	 * 微weChaPayRefundQuery支付
	 * @param WeChatPayRequest
	 * @author gwq
	 */
	@RequestMapping(value = "/weChaPayRefundQuery", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> weChaPayRefundQuery(@RequestBody WeChatPayRequest weChatPayRequest,HttpServletRequest request) {
		try {
			if (ParameterUtils.validParams(weChatPayRequest.getPaySn(), weChatPayRequest.getPayType())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}

			if (weChatPayRequest.getPayType() == PayTypeEnum.T3.getCode()) {
			} else if (weChatPayRequest.getPayType() == PayTypeEnum.T1.getCode()) {
			} else {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102, "暂不支持"), HttpStatus.OK);
			}
			Map<String, Object> outmap = null;
			PayAppKeyInfo payAppKeyInfo =orderService2.getPayAppKeyInfo(weChatPayRequest.getPayType());
			outmap = getWeChat(weChatPayRequest.getPayType()).weChaPayRefundQuery(payAppKeyInfo,weChatPayRequest.getPaySn());
			if(outmap.get("result_code")!=null&&"FAIL".equals(outmap.get("result_code").toString())){//请求失败
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseResultModel<>(outmap), HttpStatus.OK);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	/**
	 * 微weChaPayOrderquery支付
	 * @param WeChatPayRequest
	 * @author gwq
	 */
	@RequestMapping(value = "/weChaPayOrderquery", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> weChaPayOrderquery(WeChatPayRequest weChatPayRequest,HttpServletRequest request) {
		try {
			if (ParameterUtils.validParams(weChatPayRequest.getPaySn(), weChatPayRequest.getPayType())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			
			if (weChatPayRequest.getPayType() == PayTypeEnum.T3.getCode()) {
			} else if (weChatPayRequest.getPayType() == PayTypeEnum.T1.getCode()) {
			} else {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102, "暂不支持"), HttpStatus.OK);
			}
			Map<String, Object> outmap = null;
			PayAppKeyInfo payAppKeyInfo =orderService2.getPayAppKeyInfo(weChatPayRequest.getPayType());
			outmap = getWeChat(weChatPayRequest.getPayType()).weChaPayOrderQuery(payAppKeyInfo,weChatPayRequest.getPaySn());
			if(outmap.get("result_code")!=null&&"FAIL".equals(outmap.get("result_code").toString())){//请求失败
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseResultModel<>(outmap), HttpStatus.OK);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	@Autowired
	private OrderPayService orderPayService;
	
	/**
	 * MaoZeYao
	 * 微信支付会员
	 * @param response
	 * @param request
	 */
	@RequestMapping(value = "/weChaPayVip", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> weChaPayVip(@RequestBody WeChatPayRequest weChatPayRequest,HttpServletRequest request) {
		try {
			if (ParameterUtils.validParams(weChatPayRequest.getUserId(),weChatPayRequest.getPayType()))
			{
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if(weChatPayRequest.getPayType()==PayTypeEnum.T3.getCode())
			{
				if (ParameterUtils.validParams(weChatPayRequest.getOpenId()))
				{
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
				}
			}
			/*gwq  验证用户是否可以购买会员*/
			User user=userService.getUser(weChatPayRequest.getUserId());
			if(user==null){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20111), HttpStatus.OK);
			}
			if(user.getRoleId()>2){//已经是会员以上级别的了，不需要购买会员
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20275), HttpStatus.OK);
			}
			/*gwq 验证用户是否可以购买会员 结束*/
			OrderVip orderVip = talentService.createOrderVip(weChatPayRequest.getUserId(), weChatPayRequest.getPayType());
			if (orderVip == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20802), HttpStatus.OK);
			}
			PayAppKeyInfo payAppKeyInfo=getOrderService().getPayAppKeyInfo(weChatPayRequest.getPayType());
			Map<String, Object> outmap = getWeChat(weChatPayRequest.getPayType())
					.weChaPayVip(payAppKeyInfo, orderVip.getOrderSn(), orderVip.getTotalFee()
							,request.getRemoteAddr(), weChatPayRequest.getOpenId());
			return new ResponseEntity<>(new ResponseResultModel<>(outmap), HttpStatus.OK);
		} catch (IOException e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		}  catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 * MaoZeYao
	 * 微信退款
	 * @param response
	 * @param request
	 */
	@RequestMapping(value = "/weChaPayRefund", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> weChaPayRefund(@RequestBody WeChatPayRequest weChatPayRequest,
			HttpServletRequest request) {
		Map<String, Object> outmap = null;
		try {
			logger.info("weChatPayRequest："+JsonUtil.toJson(weChatPayRequest));
			if (ParameterUtils.validParams(weChatPayRequest.getAfterSn(),weChatPayRequest.getPayType(),weChatPayRequest.getIsGod())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			AfterSales afterSales = getOrderService().selectAfterSalesByCustomerServiceNumber(weChatPayRequest.getAfterSn());
			if (afterSales == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20802), HttpStatus.OK);
			}
			/**
			 * 2017-12-17 gwq 直接退款 不管售后单的状态和是否入库
			 */
			if (weChatPayRequest.getIsGod() == 1) {//一般都是人工干预了退货状态 才会走强制退款
				afterSales.setIsRefund(1);
			}
			
			if (afterSales.getStatus() == 1) {
				// 请联系工作人员同意退款后再来
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C21205), HttpStatus.OK);
			}
			
			if (afterSales.getStatus() == 3) {
				// 当前订单已经成功售后  请不要重复退钱  不给退的
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C21206), HttpStatus.OK);
			}
			
			if (afterSales.getStatus() == 4) {
				// 被拒绝了  不给退钱
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C21207), HttpStatus.OK);
			}
			
			if (afterSales.getStatus() == 2 && afterSales.getRefundId() != null || "".equals(afterSales.getRefundId())) {
				// 当前状态下  坚决不退钱
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C21210), HttpStatus.OK);
			}
			
			OrderObject orderObject = getOrderService().selectOrderObjectByOrderObjectId(afterSales.getOrderObjectId());
			if (orderObject == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20802), HttpStatus.OK);
			}
			
			// 总金额
			long totel = orderObject.getTotalFee().longValue();
			// 现在退款的金额
			long nowMoney = afterSales.getRefundMoney();
			// 已经成功退款的金额
			long successMoney = afterSalesService.getRefundSuccessMoney(orderObject.getId());

			// 表示全部退款的金额
			if (totel - successMoney <= 0 || nowMoney == 0) {
				afterSales.setRefundId("当前售后订单的实际支付金额为0");
				afterSalesService.userRefundSuccess(afterSales);
//				userEarningsService.CalculateEarningsAfterSale(afterSales.getOrderDetailId(),afterSales.getOrderObjectId());
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			}
			List<OrderPay> PayList=
					orderPayMapper.selectPaySuccessByOrderSn(orderObject.getOrderSn(),orderObject.getPayType());
			if(PayList==null||PayList.size()<=0){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
			}
			
			OrderSettlementCommision orderSettlementCommision=
					orderSettlementCommisionMapper.selectByorderID(afterSales.getOrderObjectId());
			if(orderSettlementCommision!=null&&orderSettlementCommision.getStatus()!=4){//订单相关未处理
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C21211), HttpStatus.OK);
			}
			
			OrderPay OrderPay=PayList.get(0);
			PayAppKeyInfo payAppKeyInfo = getOrderService().getPayAppKeyInfo(weChatPayRequest.getPayType());
			outmap = getWeChat(weChatPayRequest.getPayType()).weChaPayRefund(payAppKeyInfo, OrderPay.getPaySn(),
					orderObject.getTotalFee(), afterSales.getRefundMoney().intValue(),
					afterSales.getCustomerServiceNumber(), orderObject.getPayId());

			if("FAIL".equals(outmap.get("result_code"))){//请求失败 返回请求信息
				return new ResponseEntity<>(new ResponseResultModel<>(outmap.get("err_code_des").toString(),"微信回调失败"), HttpStatus.OK);
            }
			
			if ("SUCCESS".equals(outmap.get("return_code"))) {
				String refundId = outmap.get("refund_id").toString(); //微信的退款号
				// 业务代码
				afterSales.setRefundId(refundId); //保存退款流水号
				afterSalesService.userRefundSuccess(afterSales);
//				userEarningsService.CalculateEarningsAfterSale(afterSales.getOrderDetailId(),afterSales.getOrderObjectId());
				return new ResponseEntity<>(new ResponseResultModel<>(outmap), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseResultModel<>(outmap), HttpStatus.OK);
		} catch (IOException e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseResultModel<>(outmap), HttpStatus.OK);
		}
	}
	
	//add by liujie 2016-11-14
	@RequestMapping(value = "/weChaPayTransfers", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> weChaPayTransfers(@RequestBody WeChatPayRequest weChatPayRequest,
			HttpServletRequest request) {
		try {
			PayAppKeyInfo payAppKeyInfo = new PayAppKeyInfo();
			payAppKeyInfo.setAppId("wxf03adb1e865689d8");
			payAppKeyInfo.setSecret("7b6b3e64852c49ccb26d65331a543e61");
			payAppKeyInfo.setPartnerId("1251804501");
			payAppKeyInfo.setPartnerId("glelayugouglelagoulelayugou11111");
			payAppKeyInfo.setCa("d:/apiclient_cert.p12");
			Map<String, Object> outmap = getWeChat(1).weChaPayTransfers(payAppKeyInfo, "T12345678"
					, 1, request.getRemoteAddr(), weChatPayRequest.getOpenId());
			if ("SUCCESS".equals(outmap.get("return_code"))) {
				return new ResponseEntity<>(new ResponseResultModel<>(outmap), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseResultModel<>(outmap), HttpStatus.OK);
		} catch (IOException e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29910), HttpStatus.OK);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	private WeChat getWeChat(int payType) {
		WeChat theWeChat = null;
		if (payType == PayTypeEnum.T1.getCode()) {
			for (WeChat weChat : weChatList) {
				if (weChat instanceof WeChat0Impl) {
					theWeChat = weChat;
				}
			}
		} else if (payType == PayTypeEnum.T3.getCode()) {
			for (WeChat weChat : weChatList) {
				if (weChat instanceof WeChatImpl) {
					theWeChat = weChat;
				}
			}
		} else {
			theWeChat = weChatList.get(0);
		}
		return theWeChat;
	}
	
	private OrderService getOrderService() {
		return orderService2;
	}
}